export default class AudioRecorder {
    constructor() {
        this.chunks = []
        this.mediaRecorder = null
    }

    async start() {
        if (typeof navigator?.mediaDevices?.getUserMedia === 'undefined') {
            return false
        }
        const stream = await window.navigator.mediaDevices.getUserMedia({
            audio: true,
        })
        this.mediaRecorder = new MediaRecorder(stream)
        this.mediaRecorder.ondataavailable = (e) => {
            this.chunks.push(e.data)
        }
        this.mediaRecorder.start()
        return true
    }

    stop() {
        if (!this.mediaRecorder) {
            return
        }
        this.mediaRecorder.stop()
        this.mediaRecorder?.stream.getTracks().forEach((t) => t.stop())
        return new Promise((resolve) => {
            this.mediaRecorder.onstop = () => {
                const blob = new Blob(this.chunks, { type: 'audio/mp3' })
                this.chunks = []
                resolve(blob)
            }
        })
    }
}
